﻿using Dapr.Client;
using GrpcGreeter;
using Microsoft.AspNetCore.Mvc;

namespace FrontEnd.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DaprGrpcInvokeController : ControllerBase
    {
        private readonly static string _appId = "backend";
        private readonly static string _methodName = "sayhi";
        private readonly ILogger<DaprHttpInvokeController> _logger;
        private readonly DaprClient _daprClient;

        public DaprGrpcInvokeController(ILogger<DaprHttpInvokeController> logger, DaprClient daprClient)
        {
            _logger = logger;
            _daprClient = daprClient; // (推荐)构造函数注入 DaprClient
        }

        [HttpGet]
        public async Task<ActionResult> GrpcAsync()
        {
            _logger.LogInformation("构建 daprClient （gRPC）调用 BackEnd 服务");
            using var daprClient = new DaprClientBuilder().Build();
            var result = await daprClient.InvokeMethodGrpcAsync<HelloRequest, HelloReply>(_appId, _methodName, new HelloRequest { Name = "aaa" });
            return Ok(result);
        }

        [HttpGet]
        public async Task<ActionResult> Grpc2Async()
        {
            _logger.LogInformation("构造函数 DI 注入 daprClient （gRPC）调用 BackEnd 服务");
            var result = await _daprClient.InvokeMethodGrpcAsync<HelloRequest, HelloReply>(_appId, _methodName, new HelloRequest { Name = "bbb" });
            return Ok(result);
        }

    }
}
